package com.yuancheng.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串相关方法
 *
 */
public class StringUtil {

	public static String str;
	public static final String EMPTY_STRING = "";

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	/**
	 * 转换字节数组为16进制字串
	 * @param b 字节数组
	 * @return 16进制字串
	 */
	public static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	public static String MD5Encode(String origin) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes()));
		} catch (Exception ex) {
		}
		return resultString;
	}

	public static boolean isPhone(String phone) {
		String regex = "^1\\d{10}$";
		if (phone.length() != 11) {
			return false;
		} else {
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(phone);
			boolean isMatch = m.matches();
			return isMatch;
		}
	}

	/**
	 * ISO-9959-1编码转换为UTF-8
	 *
	 * @param str
	 * @return
	 */
	public static String iso88591ToUtf8(String str) {
		if (str == null) {
			return str;
		}

		try {
			return new String(str.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * emoji表情替换
	 *
	 * @param source 原字符串
	 * @return 过滤后的字符串
	 */
	public static String filterEmoji(String source) {
		if(isNotEmpty(source)){
			return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "?");
		}else{
			return source;
		}
	}

	public static String format(String phone){
		if(StringUtil.isNotEmpty(phone) && phone.length()==11){
			return phone.substring(0,3)+"*******"+phone.substring(10);
		}
		return phone;
	}

	public static String getRandomcode(int size){
		String randomcode2 = "";
		String model = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		char[] m = model.toCharArray();
		for (int j=0;j<size ;j++ ){
			char c = m[(int)(Math.random()*36)];
			randomcode2 = randomcode2 + c;
		}
		return randomcode2;
	}

	public static <K> Map<String, K> sortMapByKey(Map<String, K> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}

		Map<String, K> sortMap = new TreeMap<String, K>( new Comparator<String>(){
			public int compare(String str1, String str2) {
				return str1.compareTo(str2);
			}});

		sortMap.putAll(map);
		return sortMap;
	}

	public static String getStringByChar(String str,int size){
		String Str = "";
		if(StringUtil.isEmpty(str) || size<=0){
			return Str;
		}
		for(int i=0;i<size;i++){
			Str += str;
		}
		return Str;
	}

	/**
	 * 将以逗号分隔的字符串转换成字符串数组
	 * @param valStr
	 * @return String[]
	 */
	public static String[] StrList(String valStr){
		int i = 0;
		String TempStr = valStr;
		String[] returnStr = new String[valStr.length() + 1 - TempStr.replace(",", "").length()];
		valStr = valStr + ",";
		while (valStr.indexOf(',') > 0)
		{
			returnStr[i] = valStr.substring(0, valStr.indexOf(','));
			valStr = valStr.substring(valStr.indexOf(',')+1 , valStr.length());

			i++;
		}
		return returnStr;
	}

	/**获取字符串编码
	 * @param str
	 * @return
	 */
	public static String getEncoding(String str) {
		String encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s = encode;
				return s;
			}
		} catch (Exception exception) {
		}
		encode = "ISO-8859-1";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s1 = encode;
				return s1;
			}
		} catch (Exception exception1) {
		}
		encode = "UTF-8";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s2 = encode;
				return s2;
			}
		} catch (Exception exception2) {
		}
		encode = "GBK";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s3 = encode;
				return s3;
			}
		} catch (Exception exception3) {
		}
		return "";
	}

	/**
	 * 判断参数a是否为空，如果为空则返回b (适用与字符串等所有对象)
	 *
	 * @param <K>
	 * @param a
	 * @param b
	 * @return
	 */
	public static <K> K nvl(K a, K b) {
		return a == null ? b : a;
	}

	/**
	 * 去掉字符串前后的空格，如果为空则返回""
	 *
	 * @param a
	 * @return
	 */
	public static String clear(String a) {
		return nvl(a, "").trim();
	}

	/**
	 * 校验身份证格式是否正确
	 */
	public static boolean isIdCard(String idcard){
		return false;
	}
	/**
	 * 判断字符串为空或者长度是否等于0
	 *
	 * @param a
	 * @return
	 */
	public static boolean isEmpty(String a) {
		return "".equals(clear(a)) || "null".equals(a);
	}

	public static boolean isNotEmpty(String a) {
		return !"".equals(clear(a)) && !"null".equals(a);
	}

	/**
	 * 字符串均为空，返回true
	 * @param s
	 * @return
     */
	public static boolean isEmpty(String... s) {
		for (String a : s){
			if(!isEmpty(a)){
				return false;
			}
		}
		return true;
	}

	public static String formatDetail(String content){
		StringBuilder newsContent = new StringBuilder();
		if(!StringUtil.isEmpty(content)){
			String[] content_list = content.split("<img");
			newsContent.append(content_list[0]);
			for(int i=1;i<content_list.length;i++) {
				newsContent.append("<img");
				String[] content_list_lists = (content_list[i]+" ").split("/>");
				if (content_list_lists.length != 0) {
					String content_list_lists_0 = content_list_lists[0];
					if (content_list_lists_0.indexOf("style") != -1) {
						content_list_lists_0 = dealStyle(content_list_lists_0);
					}else{
						content_list_lists_0 += " style=\\\"vertical-align:top;\\\"";
					}
					newsContent.append(content_list_lists_0).append("/>");
					if (content_list_lists.length == 2 && "</p><p>".equals(content_list_lists[1].trim())) {
						continue;
					}else if (content_list_lists.length == 2 && "</p><p style=\\\"white-space: normal;\\\">".equals(content_list_lists[1].trim())) {
						continue;
					}else if (content_list_lists.length == 2 && "</p><p style=\"white-space: normal;\">".equals(content_list_lists[1].trim())) {
						continue;
					}else{
						for(int j=1;j<content_list_lists.length;j++){
							newsContent.append(content_list_lists[j]);
							if(j!=content_list_lists.length-1){
								newsContent.append("/>");
							}
						}
					}
				}
			}
		}
		return newsContent.toString();
	}
	//style="float:none;"
	private static String dealStyle(String content){
		StringBuilder newsContent = new StringBuilder();
		String[] content_list0 = content.split("style=\"");
		if (content_list0.length != 0) {
			newsContent.append(content_list0[0]);
			for(int i=1;i<content_list0.length;i++) {
				newsContent.append("style=\"");
				String[] content_list_lists = (content_list0[i]+" ").split("\"");
				if (content_list_lists.length != 0) {
					String content_list_lists_0 = content_list_lists[0];
					if (content_list_lists_0.indexOf("vertical-align:top;") != -1) {
					}else{
						content_list_lists_0 += ";vertical-align:top;";
					}
					newsContent.append(content_list_lists_0).append("\"");
					for(int j=1;j<content_list_lists.length;j++){
						newsContent.append(content_list_lists[j]);
						if(j!=content_list_lists.length-1){
							newsContent.append("\"");
						}
					}
				}
			}
		}else{
			String[] content_list1 = content.split("style='");
			if (content_list1.length != 0) {
				newsContent.append(content_list1[0]);
				for(int i=1;i<content_list1.length;i++) {
					newsContent.append("style='");
					String[] content_list_lists = (content_list1[i]+" ").split("'");
					if (content_list_lists.length != 0) {
						String content_list_lists_0 = content_list_lists[0];
						if (content_list_lists_0.indexOf("vertical-align:top;") != -1) {
						}else{
							content_list_lists_0 += ";vertical-align:top;";
						}
						newsContent.append(content_list_lists_0).append("'");
						for(int j=1;j<content_list_lists.length;j++){
							newsContent.append(content_list_lists[j]);
							if(j!=content_list_lists.length-1){
								newsContent.append("'");
							}
						}
					}
				}
			}
		}
		return newsContent.toString();
	}


	/**
	 * 循环截取某页列表进行分页
	 * @param dataList 分页数据
	 * @param pageSize  页面大小
	 * @param currentPage   当前页面
	 */
	public static List<Map<String,Object>> page(List<Map<String,Object>> dataList, int pageSize, int currentPage) {
		List<Map<String,Object>> currentPageList = new ArrayList<>();
		if (dataList != null && dataList.size() > 0) {
			int currIdx = (currentPage > 1 ? (currentPage - 1) * pageSize : 0);
			for (int i = 0; i < pageSize && i < dataList.size() - currIdx; i++) {
				Map<String,Object> data = dataList.get(currIdx + i);
				currentPageList.add(data);
			}
		}
		return currentPageList;
	}


	public  static void listSort(List< Map<String, Object>> orderList){
		Collections.sort(orderList, new Comparator<Map<String, Object>>() {
			@Override
			public int compare(Map<String, Object> map1, Map<String, Object> map2) {
				SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Calendar cal1 = Calendar.getInstance();
				Calendar cal2 = Calendar.getInstance();
				try {
					cal1.setTime(sdf.parse(String.valueOf(map1.get("orderTime"))));
					cal2.setTime(sdf.parse(String.valueOf(map2.get("orderTime")) ));
					int diff = DateUtils.dateDiff('s',cal1, cal2);
					if (diff > 0) {
						return -1;
					}else if (diff < 0) {
						return  1;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
				return 0; //相等为0
			}
		});
	}
}
